﻿using M_Bom.API.Application.Command.BomCommand;
using M_Bom_Domain;
using M_Bom_Domain.Dto;
using M_Bom_Repository.Interface;

using MediatR;

namespace M_Bom.API.Application.CommandHandler.BomCommandHandler
{
    public class BomShowCommandHandler : IRequestHandler<BomShowCommand, PageDto<Bom>>
    {
        protected readonly IBom bom;

        public BomShowCommandHandler(IBom bom)
        { 
            this.bom = bom;
        }

        public async Task<PageDto<Bom>> Handle(BomShowCommand request, CancellationToken cancellationToken)
        {
            var res = await bom.GetAsync(o => o.IsDeleted == false);

            if (!string.IsNullOrEmpty(request.Bombh))
            {
                res = res.Where(o => o.Bombh.Contains(request.Bombh)).ToList();
            }
            if (!string.IsNullOrEmpty(request.Chenbh))
            {
                res = res.Where(o => o.Chenbh.Contains(request.Chenbh)).ToList();
            }
            if (request.Pagesize == null)
            {
                request.Pagesize = res.Count();
            }
            if (request.Pageindex == null)
            {
                request.Pageindex = 1;
            }
            PageDto<Bom> page = new PageDto<Bom>();
            var size = request.Pagesize;
            var index = request.Pageindex;
            page.TotalCount = res.Count();
            page.PageCount = (int)Math.Ceiling(page.TotalCount * 1.0 / (int)size);
            page.list = res.OrderByDescending(o => o.Bomid).Skip(((int)index - 1) * (int)size).Take((int)size).ToList();
            return page;
        }
    }
}
